package mo.tags.backtrack.classify;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class L39 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        dfs(res, new ArrayList<>(), candidates, 0, target);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> combination, int[] candidates, int idx, int target) {
        if (idx == candidates.length) {
            return;
        }
        if (0 == target) {
            res.add(new ArrayList<>(combination));
            return;
        }
        dfs(res, combination, candidates, idx+1, target);
        if (target - candidates[idx] >= 0) {
            combination.add(candidates[idx]);
            dfs(res, combination, candidates, idx, target-candidates[idx]);
            combination.remove(combination.size()-1);
        }
    }

    public static void main(String[] args) {
        L39 test = new L39();
        System.out.println(test.combinationSum(new int[]{2, 5, 1}, 5));
    }

}
